from datetime import datetime

from examples import enums
from examples.models import Config, Product, User
from fastadmin.app import app
from fastadmin.resources import Dropdown, Field, Link, Model
from fastadmin.widgets import displays, filters, inputs


class DatetimeDisplay(displays.Display):
    async def render(self, value: datetime):
        return value.strftime("%Y-%m-%d %H:%M:%S")


@app.register
class Home(Link):
    label = "Home"
    icon = "ti ti-home"
    url = "/admin"


@app.register
class UserResource(Model):
    label = "User"
    model = User
    icon = "ti ti-user"
    page_pre_title = "user list"
    page_title = "user model"
    fields = [
        "username",
        Field(field_name="avatar", label="avatar", display=displays.Image(width="40")),
        "password",
        Field(field_name="is_active", label="IsActive", display=displays.Boolean()),
        Field(
            field_name="created_at",
            label="CreatedAt",
            display=DatetimeDisplay(),
            input=inputs.DisplayOnly(),
        ),
    ]


@app.register
class Content(Dropdown):
    class ProductResource(Model):
        label = "Product"
        model = Product
        filters = [
            filters.Enum(enum=enums.ProductType, name="type", label="ProductType"),
            filters.Datetime(name="created_at", label="CreatedAt"),
        ]
        fields = [
            "name",
            "view_num",
            "sort",
            "is_reviewed",
            "type",
            Field(field_name="image", label="image", display=displays.Image(width="40")),
            "body",
            Field(
                field_name="created_at",
                label="CreatedAt",
                display=DatetimeDisplay(),
                input=inputs.DisplayOnly(),
            ),
        ]

    label = "Content"
    icon = "ti ti-package"
    resources = [ProductResource]


@app.register
class ConfigResource(Model):
    label = "Config"
    model = Config
    icon = "ti ti-user"
    fields = [
        "label",
        "key",
        Field(field_name="value", label="Value", display=displays.Json()),
        "status",
    ]


@app.register
class GithubLink(Link):
    label = "Github"
    url = "https://github.com/long2ice"
    icon = "ti ti-brand-github"
    target = "_blank"


@app.register
class DocumentationLink(Link):
    label = "Documentation"
    url = "https://long2ice.github.io/fastadmin"
    icon = "ti ti-file-text"
    target = "_blank"
